package com.jiang.service.impl;

import com.jiang.mapper.DeptMapper;
import com.jiang.mapper.EmpMapper;
import com.jiang.pojo.Dept;
import com.jiang.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    // 调用数据库 注入接口
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;


    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }


    /**
     * 根据ID删除部门，并删除部门下的员工
     * @param id
     */
    // rollbackFor = Exception.class  —> 所有异常均回滚   默认为运行时异常才回滚
    @Transactional(rollbackFor = Exception.class)  // spring事务管理
    @Override
    public void delete(Integer id) {
        // 根据ID删除部门信息
        deptMapper.delete(id);

        // 根据部门ID 删除该部门下的所有员工信息
        empMapper.deleteByDeptId(id);
    }


    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public void getByIdUpdate(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
